package alvarodelrosal.chat.server.infraestructura;

import alvarodelrosal.chat.server.modelo.ChatConnection;
import alvarodelrosal.chat.server.modelo.ChatConversation;
import alvarodelrosal.chat.server.modelo.ChatMessage;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ChatLiveConversations {
    
    private static Set<ChatConversation> conversations = new HashSet();
    private static int conversationId= 0;
    private final static Object lock = new Object();
 
    public static void addConversation(ChatConversation conversation) {
        conversations.add(conversation);
    }
    
    public static ChatConversation getConversation (int id) {
        for (ChatConversation conversation : conversations) {
            if (conversation.getId() == id) {
                return conversation;
            }
        }
        return null;
    }
    
    public static void addMessage(ChatMessage message, int conversationId) {
        ChatConversation conversation = getConversation(conversationId);
        conversation.addMessage(message);
    }
    
    public static void addConnection(ChatConnection connection, int conversationId) {
        ChatConversation conversation = getConversation(conversationId);
        conversation.addConnection(connection);
    }
    
    public static int getNextConversationId() {
        synchronized (lock) {
            conversationId++;
            return conversationId;
        }
    }
    
    public static List<ChatConversation> getConversationsWith(int userId) {
        List<ChatConversation> conversationsWithUser = new ArrayList();
        
        for(ChatConversation conversation : conversations) {
            if (conversation.hasUser(userId)) {
                conversationsWithUser.add(conversation);
            }
        }
        
        return conversationsWithUser;
    }
    
    public static void removeConnectionFromConversation(ChatConnection connection, int conversationId) {
        ChatConversation conversation = getConversation(conversationId);
        conversation.removeConnection(connection);
        if (conversation.getConnections().size() == 0) {
            conversations.remove(conversation);
        }
    }
    
}
